package com.bb.blog.security.resource;

import com.bb.blog.security.common.OauthKeys;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.AbstractOAuth2Token;
import org.springframework.security.oauth2.server.resource.authentication.AbstractOAuth2TokenAuthenticationToken;
import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication;

import java.util.HashMap;

public class SecurityUtils {
    // 只写了 token 的形式没有写 jwt 的形式
    public static Integer loadUserId() {
        AbstractOAuth2TokenAuthenticationToken<AbstractOAuth2Token> authentication = loadAuthentication();
        return (Integer) authentication.getTokenAttributes().get(OauthKeys.USER_ID);
    }

    // 获取用户的 用户名
    public static String loadUsername() {
        AbstractOAuth2TokenAuthenticationToken<AbstractOAuth2Token> authentication = loadAuthentication();
        return (String) authentication.getTokenAttributes().get(OauthKeys.SUB);

    }

    @SuppressWarnings("unchecked")
    public static AbstractOAuth2TokenAuthenticationToken<AbstractOAuth2Token> loadAuthentication() {
        return (AbstractOAuth2TokenAuthenticationToken<AbstractOAuth2Token>)
                SecurityContextHolder.getContext().getAuthentication();
    }
}
